#!/usr/bin/python3
import time
try:
    import MySQLdb #win32 platform
except ImportError:
    import mysql.connector as MySQLdb #linux/Ubuntu
import logging
from config import DB

log=logging.getLogger('bishop')

def insert_db(site,news,text,complit='waiting'):
    db=MySQLdb.connect(user=DB['user'],passwd=DB['passwd'],db=DB['db'])
    c=db.cursor()
    try:
        c.execute("""INSERT INTO bishop_tbl VALUES(id,'%s','%s','%s','%s')""" % (site,news,text,complit))
        db.commit()
        c.close()
    except:
        log.exception("exception message")
        c.close()

def select_db(site='',data='waiting'):
    if data=='waiting':
        db=MySQLdb.connect(user=DB['user'],passwd=DB['passwd'],db=DB['db'])
        c=db.cursor()
        c.execute("""SELECT id,site,text FROM bishop_tbl WHERE complit='waiting' """)
        sit=c.fetchall()
        spisok=list(sit)
        c.close()
    else:
        db=MySQLdb.connect(user=DB['user'],passwd=DB['passwd'],db=DB['db'])
        c=db.cursor()
        c.execute("""SELECT news FROM bishop_tbl WHERE site='%s' ORDER BY id DESC LIMIT 100 ;""" % site)
        sit=c.fetchall()
        spisok=list(sit)
        c.close()
    return spisok

def update_db(id_):
    db=MySQLdb.connect(user=DB['user'],passwd=DB['passwd'],db=DB['db'])
    c=db.cursor()
    c.execute("""UPDATE bishop_tbl SET complit='suc' WHERE id=%s; """ % id_)
    db.commit()
    c.close()
    return

def GetIdUser():
    db=MySQLdb.connect(user=DB['user'],passwd=DB['passwd'],db=DB['db'])
    cursor=db.cursor()
    try:
        cursor.execute("""Select * from Site_tbl """ )
        response=cursor.fetchall()
        cursor.close()
        return response
    except:
        log.exception("exception message")
        cursor.close()

def GetUserEmail(sql):
    db=MySQLdb.connect(user=DB['user'],passwd=DB['passwd'],db=DB['db'])
    cursor=db.cursor()
    try:
        cursor.execute("""Select email from login_tbl where %s """ % sql)
        response=cursor.fetchall()
        cursor.close()
        return response
    except:
        log.exception("exception message")
        cursor.close()